﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace Batsman_Record
{
    public class BatsmanStats
    {
        private Dictionary<string, string> NametoFileMap;

        public BatsmanStats()
        {
            NametoFileMap = new Dictionary<string, string>();
        }
        /// <summary>
        /// Creates Batsman or Bowler Statistics based on playerType 
        /// PlayerType True for Batsman, False for Bowler (is a hack currently, will generalize later)
        /// </summary>
        /// <param name="filePath">FilePath</param>
        /// <param name="InningsWise">Whether Innings Wise or Not</param>
        /// <param name="PlayerType">Batsman = True, Bowler = False</param>
        public void CreateBatsmanStats(string filePath, bool InningsWise, bool playerType)
        {            
            var lines = File.ReadAllLines(filePath);
            var innings_num = string.Empty;
            string modifiedFilePath = string.Empty;
            if (playerType)
            {
                modifiedFilePath = Path.Combine(Path.GetDirectoryName(filePath), "Batsman_Records");
            }
            else
            {
                modifiedFilePath = Path.Combine(Path.GetDirectoryName(filePath), "Bowler_Records");
            }

            if (InningsWise)
            {
                innings_num = Path.GetFileNameWithoutExtension(filePath);
                if (!Directory.Exists(Path.Combine(modifiedFilePath, "innings1")))
                {
                    Directory.CreateDirectory(Path.Combine(modifiedFilePath, "innings1"));
                }
                if (!Directory.Exists(Path.Combine(modifiedFilePath, "innings2")))
                {
                    Directory.CreateDirectory(Path.Combine(modifiedFilePath, "innings2"));
                }
            }
            var count = lines.Length;
            for (int i = 1; i < count; i++ )
            {
                var line = Regex.Replace(lines[i], "( )+", " ");
                var words = line.Split(' ');
                var batsmanName = string.Empty;

                try
                {
                    for (int j = 0; j < 10; j++)
                    {
                        if (playerType)
                        {
                            if (string.CompareOrdinal(words[j], "to") == 0)
                            {
                                if (!string.IsNullOrEmpty(innings_num))
                                {
                                    var innings = innings_num.Substring(innings_num.LastIndexOf("test", StringComparison.OrdinalIgnoreCase) + "test".Length + 2, 1);
                                    switch (Convert.ToInt32(innings))
                                    {
                                        case 1: batsmanName = @"innings1\";
                                            break;
                                        case 2: batsmanName = @"innings2\";
                                            break;
                                        default: throw new IndexOutOfRangeException("bad innings no.");
                                    }
                                }
                                batsmanName = batsmanName + words[j + 1];
                                break;
                            }
                            if (j == 9)
                            {
                                throw new IndexOutOfRangeException("bad data");
                            }
                        }
                        else
                        {
                            if (string.CompareOrdinal(words[j], "to") == 0)
                            {
                                if (!string.IsNullOrEmpty(innings_num))
                                {
                                    var innings = innings_num.Substring(innings_num.LastIndexOf("test", StringComparison.OrdinalIgnoreCase) + "test".Length + 2, 1);
                                    switch (Convert.ToInt32(innings))
                                    {
                                        case 1: batsmanName = @"innings1\";
                                            break;
                                        case 2: batsmanName = @"innings2\";
                                            break;
                                        default: throw new IndexOutOfRangeException("bad innings no.");
                                    }
                                }
                                for (int k = 1; k < j; k++)
                                {
                                    batsmanName = batsmanName + words[k];
                                }
                                break;
                            }

                        }

                    }

                    if (NametoFileMap.ContainsKey(batsmanName))
                    {
                        if (line.IndexOf("end of over", StringComparison.OrdinalIgnoreCase) > 0)
                        {
                            File.AppendAllText(NametoFileMap[batsmanName], "\n" + line.Substring(0, line.IndexOf("end of over", StringComparison.OrdinalIgnoreCase)));
                        }
                        else
                        {
                            File.AppendAllText(NametoFileMap[batsmanName], "\n" + line);
                        }

                    }

                    else
                    {
                        NametoFileMap.Add(batsmanName, Path.Combine(modifiedFilePath, batsmanName + ".txt"));

                        if (line.IndexOf("end of over", StringComparison.OrdinalIgnoreCase) > 0)
                        {
                            File.AppendAllText(NametoFileMap[batsmanName], "\n" + line.Substring(0, line.IndexOf("end of over", StringComparison.OrdinalIgnoreCase)));
                        }
                        else
                        {
                            File.AppendAllText(NametoFileMap[batsmanName], "\n" + line);
                        }
                    }
                }
                catch (IndexOutOfRangeException e)
                {
                    e.GetType();
                    Trace.WriteLine("Some lines have bad data");
                }
                catch (ArgumentException e)
                {
                    e.GetType();
                    Trace.WriteLine("Useless Data");
                }

            }
        }
    }
}
